package com.ruoyi.web.controller.persion.service;

import com.ruoyi.web.Server.sys.UserService;
import com.ruoyi.web.controller.persion.entity.Favorite ;
import com.ruoyi.web.controller.persion.mapper.FavoriteMapper ;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class FavoriteServiceImpl implements IFavoriteService {

    @Autowired
    final UserService userService;
    @Autowired
    private FavoriteMapper favoriteMapper;

    public FavoriteServiceImpl(UserService userService) {
        this.userService = userService;
    }

    @Override
    public Favorite selectFavoriteById(Long favoriteId) {
        return favoriteMapper.selectFavoriteById(favoriteId);
    }

    @Override
    public List<Favorite> selectFavoriteList() {
        int userId = userService.getUserId();
        return favoriteMapper.selectFavoriteList(userId);
    }

    @Override
    public int insertFavorite(Favorite favorite) {
        return favoriteMapper.insertFavorite(favorite);
    }

    @Override
    public int updateFavorite(Favorite favorite) {
        return favoriteMapper.updateFavorite(favorite);
    }

    @Override
    public int deleteFavoriteById(Long favoriteId) {
        return favoriteMapper.deleteFavoriteById(favoriteId);
    }

    @Override
    public int deleteFavoriteByIds(Long[] favoriteIds) {
        return favoriteMapper.deleteFavoriteByIds(favoriteIds);
    }

    @Override
    public boolean toggleFavorite(Long userId, Long seedId) {
        if (favoriteMapper.checkFavoriteExists(userId, seedId) > 0) {
            // 已收藏，执行取消收藏
            Favorite favorite = new Favorite();
            favorite.setUserId(userId);
            favorite.setSeedId(seedId);
            favorite.setStatus("1"); // 标记为删除状态
            favoriteMapper.updateFavorite(favorite);
            return false;
        } else {
            // 未收藏，执行收藏
            Favorite favorite = new Favorite();
            favorite.setUserId(userId);
            favorite.setSeedId(seedId);
            favorite.setStatus("0"); // 正常状态
            favoriteMapper.insertFavorite(favorite);
            return true;
        }
    }

    @Override
    public List<Favorite> getUserFavorites(Long userId) {
        return favoriteMapper.selectFavoritesByUserId(userId);
    }

    @Override
    public boolean isFavorite(Long userId, Long seedId) {
        return favoriteMapper.checkFavoriteExists(userId, seedId) > 0;
    }
}